<?php

namespace AppBundle\Util\Gateway;

use GuzzleHttp\Client;
use AppBundle\Log\LoggerTrait;
use AppBundle\Exception\GatewayException;
use AppBundle\Exception\GatewayReturnErrorException;

/**
 * Description of GatewayUtil
 *
 * @author yihao
 */
class GatewayUtil
{
    use LoggerTrait;

    /**
     * 解析XML文件内容Body部分为Array
     * @param $xmlStr
     * @return array
     * @throws GatewayException
     * @throws GatewayReturnErrorException
     */
    public function parseXML($xmlStr)
    {
        $this->logInfo('[Gateway|parseArrayXML] Trying to parse xml string.', array(
            'xmlStr' => $xmlStr,
        ));

        $xml = simplexml_load_string($xmlStr);

        $resultNode = $xml->xpath('/soapenv:Envelope/soapenv:Body/gateway:NoAS400')[0];

        $return = $this->parse2XML($resultNode);
        return $return;
    }

    public function parse2XML($Nodes)
    {
        $nodeArr = $Nodes->children('http://www.agree.com.cn/GDBGateway');
        $result = array();
        foreach ($nodeArr as $node) {
            $name = $node->getName();
            if ($name == 'fie') {
                $attrs = $node->attributes();
                foreach ($attrs as $attr) {
                    $attrName = $attr->getName();
                    if ($attrName === 'name') {
                        $result[(string)$attr][] = $this->parse2XML($node);
                        break;
                    }
                }

            }
            if ($name == 'field') {
                $attrs = $node->attributes();
                foreach ($attrs as $attr) {
                    $attrName = $attr->getName();
                    if ($attrName === 'name') {
                        $result[(string)$attr] = (string)$node;
                        break;
                    }
                }
            }

        }
        return $result;
    }

}
